﻿namespace SupportSystemUI.Controls.Basic
{
    using System;
    using System.ComponentModel;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using SupportSystemDB;

    /// <summary>
    /// Interaction logic for IntroScreen.xaml
    /// </summary>
    public partial class IntroScreen : UserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="IntroScreen"/> class.
        /// </summary>
        public IntroScreen()
        {
            this.InitializeComponent();

            this.usernameTextbox.TextChanged += (sender, args) => { this.CheckInput(); };
            this.passwordTextbox.PasswordChanged += (sender, args) => { this.CheckInput(); };
        }

        /// <summary>
        /// Handler called when the control finishes loading.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Routed event arguments.</param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.CheckInput();
            this.usernameTextbox.Focus();

            DoubleAnimation animation = new DoubleAnimation
            {
                From = 0,
                To = 360,
                Duration = new Duration(TimeSpan.FromSeconds(2)),
                RepeatBehavior = RepeatBehavior.Forever,
            };

            RotateTransform rotation = new RotateTransform
            {
                CenterX = this.loopIcon.ActualWidth / 2,
                CenterY = this.loopIcon.ActualHeight / 2,
            };

            rotation.BeginAnimation(RotateTransform.AngleProperty, animation);
            this.loopIcon.RenderTransform = rotation;

            KeyEventHandler enterKeyPressed = (sender2, args2) =>
            {
                if (args2.Key == Key.Enter)
                {
                    this.KeysIcon_MouseUp(null, null);
                }
            };

            this.usernameTextbox.KeyDown += enterKeyPressed;
            this.passwordTextbox.KeyDown += enterKeyPressed;
        }

        /// <summary>
        /// Validates user input, and if successful, contacts the server for reference.
        /// </summary>
        /// <returns>True if input was correct, false otherwise.</returns>
        private bool CheckInput()
        {
            if (string.IsNullOrWhiteSpace(this.usernameTextbox.Text))
            {
                this.errorLabel.Content = "Please enter your username.";
                return false;
            }
            else if (string.IsNullOrWhiteSpace(this.passwordTextbox.Password))
            {
                this.errorLabel.Content = "Please enter your password.";
                return false;
            }
            else
            {
                this.errorLabel.Content = string.Empty;
                return true;
            }
        }

        /// <summary>
        /// Handler called when the mouse is up above the KeysIcon content control.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">Key event arguments.</param>
        private void KeysIcon_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (this.CheckInput())
            {
                this.errorLabel.Content = string.Empty;
                this.keysIcon.Visibility = Visibility.Hidden;
                this.loopIcon.Visibility = Visibility.Visible;

                BackgroundWorker worker = new BackgroundWorker();

                worker.DoWork += (obj, args) =>
                {
                    LogInResults result = AppController.Instance.LogIn(
                        (args.Argument as dynamic).Username,
                        (args.Argument as dynamic).Password);

                    Member profile = (result == LogInResults.LogInSucceeded)
                        ? AppController.Instance.GetMemberProfile((args.Argument as dynamic).Username)
                        : null;

                    args.Result = new
                    {
                        Result = result,
                        Profile = profile,
                    };
                };

                worker.RunWorkerCompleted += (obj, args) =>
                {
                    this.keysIcon.Visibility = Visibility.Visible;
                    this.loopIcon.Visibility = Visibility.Hidden;
                    LogInResults result = (args.Result as dynamic).Result;

                    this.errorLabel.Content = (Attribute.GetCustomAttribute(
                        result.GetType().GetField(result.ToString()),
                        typeof(DescriptionAttribute)) as DescriptionAttribute).Description;

                    if (result == LogInResults.LogInSucceeded)
                    {
                        Global.Instance.CurrentProfile = (args.Result as dynamic).Profile;
                        Global.Instance.MainSlidePanel.Push(new MainScreen());
                    }
                };

                worker.RunWorkerAsync(new
                {
                    Username = this.usernameTextbox.Text,
                    Password = this.passwordTextbox.Password,
                });
            }
        }
    }
}
